package com.luoxc.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.luoxc.pojo.Result;
import com.luoxc.utils.JwtHandle;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
* 拦截器
* */
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("执行了拦截器------");
        // 1.判断是否携带token值
        String token = request.getHeader("token");
        if(!StringUtils.hasLength(token)){
            // 响应错误信息给客户端
            Result error = Result.error("not_null");
            // 手动转换为json
            String jsonString = JSONObject.toJSONString(error);
            // 响应数据给浏览器
            response.getWriter().write(jsonString);
            return false;
        }
        // 2.判断token值是否正确
        try {
            JwtHandle.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            // 响应错误信息给客户端
            Result error = Result.error("not_null");
            // 手动转换为json
            String jsonString = JSONObject.toJSONString(error);
            // 响应数据给浏览器
            response.getWriter().write(jsonString);
            return false;
        }
        // 3.放行
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        System.out.println("放行了拦截器------");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        System.out.println("渲染完成了------");
    }

}
